<?php


namespace App\Service\DataBase;


use App\Service\Dir;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;



class Bak
{
    protected $db; // 指定数据库操作（实例化的数据库操作）
    protected $error;

    // 数据库操作
    public function __construct()
    {
    }

    // 返回错误信息
    public function getError()
    {
        return $this->error;
    }

    // 备份
    public function toBak($db_name, $bakPath, $connect = '')
    {
        $connect = $connect ? $connect : Config::get('database.default');
        $db_sql  = "SHOW DATABASES LIKE '$db_name';";
        $db_info = DB::connection($connect)->query($db_sql);
        if(empty($db_info)){
            $this->error = '数据库不存在！！';

            return false;
        }

        ## 所有数据
        $cline      = chr(10);
        $tabels_sql = "show tables from `$db_name`;";
        $tabels_sql = "select table_name from information_schema.tables where table_schema='$db_name' and table_type='base table';";
        $tabel_list = DB::connection($connect)->select($tabels_sql);

        ## 组合导出的sql语句
        $bak_sql = "-- ----------------------------".$cline;
        $bak_sql .= "-- 日期：".date("Y-m-d H:i:s", time()).$cline;
        $bak_sql .= "-- 本程序由小学生制作,本程序不适合处理超大量数据".$cline;
        $bak_sql .= "-- ----------------------------".$cline.$cline;
        $bak_sql .= "-- ----------------------------".$cline;
        foreach($tabel_list as $table){
            ## 获取数据表结构
            $table_name = $table->table_name;
            $_structure = DB::connection($connect)->select("SHOW CREATE TABLE `$db_name`.`$table_name`;"); // 多列
            $_structure = $_structure[0]; // shtmlspecialchars_decode
            $careaName  = 'Create Table';
            $createSql  = $_structure->$careaName;

            ## 数据表结构语句
            $bak_sql .= "-- Table structure for `".$table_name."`".$cline;
            $bak_sql .= "-- ----------------------------".$cline;
            $bak_sql .= "DROP TABLE IF EXISTS `".$table_name."`;".$cline.$cline;
            $bak_sql .= "-- ".htmlspecialchars_decode($_structure->Table).$cline;
            $bak_sql .= htmlspecialchars_decode($_structure->$careaName).';'.$cline;

            ## 导出数据
            ## 备份的时候 导出系统表数据的时候
            $_list   = DB::connection($connect)->select("SELECT * FROM `$db_name`.`$table_name`");
            $bak_sql .= "-- ----------------------------".$cline;
            $bak_sql .= "-- Records for `".$table_name."`".$cline;
            $bak_sql .= "-- ----------------------------".$cline;

            // 插入数据
            foreach($_list as $key => $row){
                $make_sql = '';
                foreach($row as  $_key=>$_val){
                    if(!isset($_val)){
                        $make_sql .= " NULL,";
                    } else{
                        $_val     = is_numeric($_val) ? $_val : ($_val == 0 ? $_val : addslashes($_val));
                        $make_sql .= " \"".$_val."\",";
                    }
                }

                $make_sql   = substr($make_sql, 0, -1); ## 取消最后一个逗号
                $insert_sql = "INSERT INTO `$table_name` VALUES   ( $make_sql );".$cline;
                $bak_sql    .= $insert_sql;
            }

            $bak_sql .= "-- ----------------------------".$cline.$cline.$cline;

            echo ' == 备份本地数据表：'.$table_name.$cline;
        }

        // 路径
        if(!is_dir($bakPath)){
            (new Dir())->makeDir($bakPath);
        }

        ## 整理数据，生成统一文件
        $filename = $db_name.'-'.date("Y-m-d H：i：s").".sql";
        file_put_contents($bakPath.$filename, $bak_sql);

        return true;
    }

}
